/**
 * 
 */
package com.zznode.client.wlanpolling.test;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Node;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.WLanContext;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.model.WirelessEvnInfo;
import com.zznode.client.wlanpolling.service.Wifi;
import com.zznode.client.wlanpolling.service.WifiGroup;
import com.zznode.client.wlanpolling.service.net.EnumHttpMethod;
import com.zznode.client.wlanpolling.service.net.HttpCallback;
import com.zznode.client.wlanpolling.service.net.HttpException;
import com.zznode.client.wlanpolling.service.net.HttpExecutorFactory;
import com.zznode.client.wlanpolling.service.net.HttpGetExecutor;
import com.zznode.client.wlanpolling.service.net.HttpParam;
import com.zznode.client.wlanpolling.service.xml.XmlParserException;
import com.zznode.client.wlanpolling.service.xml.XmlXPathAdaptor;
import com.zznode.client.wlanpolling.utils.NetworkUtils;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;

/**
 * 
 *
 */
public class WirelessEnvActivity extends Activity implements HttpCallback {
	
	private WirelessEnvAdaptor wirelessEnvAdaptor;
	private WLANPollingApplication application;

	private WifiReceiver receiverWifi;
	private WifiManager wifiManager;
	private Timer scanTimer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wirelessenv);
		
		application = (WLANPollingApplication)getApplication();
		ExpandableListView listView = (ExpandableListView)findViewById(R.id.wirelessList);
		wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		
		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);
		Button btn = new Button(this);
		btn.setBackgroundResource(R.drawable.btn_testsel);
		btn.setText("进入下一步");
		btn.setTextColor(Color.WHITE);
		btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				saveAndNext();
			}
			
		});
		
		LayoutParams params = new LayoutParams(250, LayoutParams.WRAP_CONTENT);
		params.topMargin = 10;
		params.bottomMargin = 10;
		params.gravity = Gravity.CENTER_HORIZONTAL;
		ll.addView(btn, params);
		
		listView.addFooterView(ll);
		
		Map<String, WifiGroup> wifiGroups = application.getContext().getApGroupList();
		List<Wifi> wifis = new ArrayList<Wifi>();
		for(WifiGroup wifiGroup : wifiGroups.values()) {
			wifis.addAll(wifiGroup.getApList());
		}
		
		WLANPollingApplication appliction = (WLANPollingApplication)getApplication();
		WLanContext context = appliction.getContext();

		WirelessEvnInfo info = new WirelessEvnInfo();
		
		if(context.getCurrentWifi() != null) {
			info.setWirelessChannel(NetworkUtils.getChannel(context.getCurrentWifi().getFrequency()) + "");
			info.setFrequency(context.getCurrentWifi().getFrequency() +"");
		}
		
		wirelessEnvAdaptor = new WirelessEnvAdaptor(this, info, context, wifis);
		
		listView.setAdapter(wirelessEnvAdaptor);
		listView.setGroupIndicator(null);
		
		for(int i = 0; i < wirelessEnvAdaptor.getGroupCount(); i++) {
			listView.expandGroup(i);
		}
		
		wirelessEnvAdaptor.calculateCurve(wifis);	
		
		receiverWifi = new WifiReceiver();
		getApplicationContext().registerReceiver(receiverWifi, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		
		scanTimer = new Timer();
		scanTimer.schedule(scanTimerTask, 1000, 1000*10);
		
		loadWirelessInfoFromServer();
	}
	
	private void loadWirelessInfoFromServer() {
		HttpGetExecutor executor = (HttpGetExecutor) HttpExecutorFactory.createHttpExecutor(EnumHttpMethod.GET);
		executor.setUrl(WLanPollingUtils.getWirelessInfoURL());
		executor.addParam(new HttpParam("apmac", application.getContext().getCurrentWifi().getBSSID()));
		executor.asyncExecute(this, 1);
	}
	
	@Override
	public void onReceiveData(byte[] data, HttpException exp, int tag) {
		if(tag == 1) {
			XmlXPathAdaptor xPath = null;
			try {
				xPath = new XmlXPathAdaptor(new ByteArrayInputStream(data));
			} catch (final XmlParserException e) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), e.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				});
			}
			
			if(xPath != null) {
				try {
					final WirelessEvnInfo info = new WirelessEvnInfo();
					//使用的无线信道
					Node WIRELESS_CHANNEL = (Node)xPath.evaluate("/NODE/WIRELESS_CHANNEL", XPathConstants.NODE);
					if(WIRELESS_CHANNEL.getTextContent() != null) {
						info.setWirelessChannel(WIRELESS_CHANNEL.getTextContent());
					}
					
					//配置的无线模式
					Node RADIO_MODEL_CONFIG = (Node)xPath.evaluate("/NODE/RADIO_MODEL_CONFIG", XPathConstants.NODE);
					if(RADIO_MODEL_CONFIG.getTextContent() != null) {
						info.setWirelessMode(RADIO_MODEL_CONFIG.getTextContent());
					}
					
					//最大的发射功率
					Node MAX_TXPWR_LVL  = (Node)xPath.evaluate("/NODE/MAX_TXPWR_LVL", XPathConstants.NODE);
					if(MAX_TXPWR_LVL.getTextContent() != null) {
						info.setWirelessPower(MAX_TXPWR_LVL.getTextContent());
					}
					
					//配置的VLAN_ID
					Node VLAN_ID = (Node)xPath.evaluate("/NODE/VLAN_ID", XPathConstants.NODE);
					if(VLAN_ID.getTextContent() != null) {
						info.setWirelessVlanid(VLAN_ID.getTextContent());
					}
					
					//最大关联终端数
					Node MAX_STATIONNUM_PERMITTED  = (Node)xPath.evaluate("/NODE/MAX_STATIONNUM_PERMITTED ", XPathConstants.NODE);
					if(MAX_STATIONNUM_PERMITTED.getTextContent() != null) {
						info.setWirelessRelativeclient(MAX_STATIONNUM_PERMITTED.getTextContent());
					}
					
					//Beacon帧发送间隔
					Node BEACON = (Node)xPath.evaluate("/NODE/BEACON", XPathConstants.NODE);
					if(BEACON.getTextContent() != null) {
						info.setBeacon(BEACON.getTextContent());
					}
					
					//信道自动分配开关（开/关）
					Node RADIOCHANNEL_AUTOSELECT_ENABLE = (Node)xPath.evaluate("/NODE/RADIOCHANNEL_AUTOSELECT_ENABLE", XPathConstants.NODE);
					if(RADIOCHANNEL_AUTOSELECT_ENABLE.getTextContent() != null) {
						info.setRadioChannel_AutoSelect_enable(RADIOCHANNEL_AUTOSELECT_ENABLE.getTextContent());
					}
					
					
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							wirelessEnvAdaptor.setWirelessEvnInfo(info);
						}
					});
				} catch (XmlParserException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if(receiverWifi != null) {
			getApplicationContext().unregisterReceiver(receiverWifi);
			receiverWifi = null;
		}
		if(scanTimer != null) {
			scanTimer.cancel();
			scanTimer.purge();
			scanTimer = null;
		}
		super.onDestroy();
	}

	private void startScanWifi() {
		wifiManager.startScan();
	}
	
	protected void saveAndNext(){
		//save to db
		WLANPollManager.getWLANPollManager().updateWirelessEnv(application.getApplicationContext(),
				application.getContext().getCurrentWifi().getBSSID(), wirelessEnvAdaptor.getSameFrequencyInterference(),
				wirelessEnvAdaptor.getNearbyFrequencyInterference());
		if(getParent() instanceof WLANPollingTabActivity) {
			((WLANPollingTabActivity)getParent()).selectNextTab();
		} else {
			startActivity(new Intent(this, PollTestActivity.class));
		}
	}
	
	public void refreshWifiList(List<Wifi> wifiList) {
		wirelessEnvAdaptor.setWifiList(wifiList);
		wirelessEnvAdaptor.calculateCurve(wifiList);
	}
	
	private TimerTask scanTimerTask = new TimerTask() {
		
		@Override
		public void run() {
			startScanWifi();
		}
	};
	
	class WifiReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			//Log.d("test", "onReceive");
			List<ScanResult> scanResults = wifiManager.getScanResults();
			
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			final List<Wifi> wifiList = new ArrayList<Wifi>();
			for (ScanResult result : scanResults) {
				Wifi wifi = new Wifi(result, null);
				if(wifi.getBSSID().equals(wifiInfo.getBSSID())) {
					wifi.setSelected(true);
				} else {
					wifi.setSelected(false);
				}
				wifiList.add(wifi);
			}
			
			runOnUiThread(new Runnable() {
				@Override
				public void run() {		
					refreshWifiList(wifiList);
				}
			});
		}
	}
}
